<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin\Account;
use App\Models\Admin\AccountMoneyChange;
use App\Models\Admin\Goods;
use App\Models\Admin\GoodsRepertoryLog;
use App\Models\Admin\StockOrderGoods;
use App\Models\Admin\Store;
use App\Tools\Texcel;

class FinancialController extends BaseController
{

    /**
     * 代理商商品流水
     */
    public function agentGoodsList()
    {
        $where['start']     = $this->requestArr['start'];
        $where['end']       = $this->requestArr['end'];
        $where['store_id']  = $this->requestArr['store_id'];
        $where['goods_ids'] = $this->requestArr['goods_id_select'];
        $limit              = $this->requestArr['export_excel'] == 1 ? 100000 : 15;
        $list = StockOrderGoods::getOutboundList($where,$limit);

        if ($this->requestArr['export_excel'] == 1) {
            $title    = '财务报表-代理商商品流水';
            $titleArr = ['订单编号', '日期', '商品编号', '商品名称', '代理商', '零售价格/元', '代理价格/元', '数量'];
            $dataArr  = [];
            foreach ($list as $k => $item) {
                $dataArr[$k]['order_sn']     = $item['order_sn'];
                $dataArr[$k]['created_at']   = $item['created_at'];
                $dataArr[$k]['goods_sn']     = $item['goods_sn'];
                $dataArr[$k]['goods_name']   = $item['goods_name'];
                $dataArr[$k]['store_name']   = $item['store_name'];
                $dataArr[$k]['old_price']    = $item['old_price'];
                $dataArr[$k]['goods_price']  = $item['goods_price'];
                $dataArr[$k]['goods_number'] = $item['goods_number'];
            }
            if (empty($dataArr)) {
                view()->share('layout_message', '暂无导出数据');
            } else {
                Texcel::exportExcelHtml($title, $titleArr, $dataArr);
            }
            exit();
        }

        $store = Store::getBaseList();
        if (!empty($where['start'])) {
            $list->appends(['start' => $where['start']])->render();
        }
        if (!empty($where['end'])) {
            $list->appends(['end' => $where['end']])->render();
        }
        if (!empty($where['store_id'])) {
            $list->appends(['store_id' => $where['store_id']])->render();
        }
        if (!empty($where['goods_ids'])) {
            $list->appends(['goods_id_select' => $where['goods_ids']])->render();
        }

        return view('admin/financial/agentGoodsList', ['data' => $list, 'store' => $store]);
    }

    /**
     * 代理商资金流水
     */
    public function agentFinancialList()
    {
        // e_account_money_change 表中的 account_id、to_account_id 是e_account表中的 id
        $where['start'] = $this->requestArr['start'];
        $where['end']   = $this->requestArr['end'];

        $accountIds = Array();
        $storeId = $this->requestArr['store_id'];
        if ($storeId) {
            $accounts = Account::where(['account_id' => $storeId])->get();
            foreach ($accounts as $v) {
                $accountIds[] = $v['id'];
            }
        }
        $where['account_ids'] = $accountIds;

        $limit = $this->requestArr['export_excel'] == 1 ? 100000 : 15;
        $list  = AccountMoneyChange::getList($where,$limit);

        foreach ($list as &$value) {
            $value->hk_recharge = 0;
            $value->glf_recharge = 0;
            $value->hk_out = 0;
            $value->glf_out = 0;
            $value->yf = 0;
            $value->glf_balance = 0;
            $value->hk_balance = 0;
            $accountId = 0;
            if ($value->consume_type == 1) {
                $accountId = $value->to_account_id;
                $value->hk_recharge = $value->money;
                $value->hk_balance  = $value->to_money_after;
            } elseif ($value->consume_type == 2) {
                $accountId = $value->to_account_id;
                $value->glf_recharge = $value->money;
                $value->glf_balance  = $value->to_money_after;
            } elseif ($value->consume_type == 3) {
                $accountId = $value->account_id;
                $value->hk_out = $value->money;
                $value->hk_balance = $value->money_after;
            } elseif ($value->consume_type == 4) {
                $accountId = $value->account_id;
                $value->glf_out = $value->money;
                $value->glf_balance = $value->money_after;
            } elseif ($value->consume_type == 5) {
                $accountId = $value->account_id;
                $value->yf = $value->money;
                $value->hk_recharge = $value->money_after;
            } elseif ($value->consume_type == 6) {
                $accountId = $value->account_id;
                $value->yf = $value->money;
                $value->glf_balance = $value->money_after;
            }
            $value->created_at = date("Y-m-d H:i:s",$value->created_at);
            // 获取代理商名称
            $store = Account::from('account as a')
                ->where(['a.id' => $accountId])
                ->leftjoin('store as s', 'a.account_id', '=', 's.id')
                ->select(['s.store_name'])
                ->first();
            $value->store_name = $store['store_name'];
        }

        if ($this->requestArr['export_excel'] == 1) {
            $title    = '财务报表-代理商资金流水';
            $titleArr = ['序号', '日期', '代理商', '管理费入账', '货款入账', '管理费出账', '货款出账', '运费', '管理费余额', '货款余额'];
            $dataArr  = [];
            foreach ($list as $k => $item) {
                $dataArr[$k]['id']           = $item->id;
                $dataArr[$k]['created_at']   = $item->created_at;
                $dataArr[$k]['store_name']   = $item->store_name;
                $dataArr[$k]['hk_recharge']  = $item->hk_recharge;
                $dataArr[$k]['glf_recharge'] = $item->glf_recharge;
                $dataArr[$k]['hk_out']       = $item->hk_out;
                $dataArr[$k]['glf_out']      = $item->glf_out;
                $dataArr[$k]['yf']           = $item->yf;
                $dataArr[$k]['glf_balance']  = $item->glf_balance;
                $dataArr[$k]['hk_balance']   = $item->hk_balance;
            }
            if (empty($dataArr)) {
                view()->share('layout_message', '暂无导出数据');
            } else {
                Texcel::exportExcelHtml($title, $titleArr, $dataArr);
            }
            exit();
        }

        $statistic = Array();
        if ($storeId) {
            $all = AccountMoneyChange::getList($where,100000);
            $statistic['hk_recharge'] = 0;
            $statistic['glf_recharge'] = 0;
            $statistic['hk_out'] = 0;
            $statistic['glf_out'] = 0;
            $statistic['yf'] = 0;
            foreach ($all as $al) {
                if ($al->consume_type == 1) {
                    $accountId = $al->to_account_id;
                    $statistic['hk_recharge']= $statistic['hk_recharge'] + $al->money;
                } elseif ($al->consume_type == 2) {
                    $accountId = $al->to_account_id;
                    $statistic['glf_recharge'] = $statistic['glf_recharge'] + $al->money;
                } elseif ($al->consume_type == 3) {
                    $accountId = $al->to_account_id;
                    $statistic['hk_out'] = $statistic['hk_out'] + $al->money;
                } elseif ($al->consume_type == 4) {
                    $accountId = $al->to_account_id;
                    $statistic['glf_out']= $statistic['glf_out'] + $al->money;
                } elseif ($al->consume_type == 5) {
                    $accountId = $al->to_account_id;
                    $statistic['yf'] = $statistic['yf'] + $al->money;
                } elseif ($al->consume_type == 6) {
                    $accountId = $al->to_account_id;
                    $statistic['yf'] =$statistic['yf'] + $al->money;
                }
            }
            // 获取代理商名称
            $store = Account::from('account as a')
                    ->where(['a.id' => $accountId])
                    ->leftjoin('store as s', 'a.account_id', '=', 's.id')
                    ->select(['s.store_name'])
                    ->first();
            $statistic['store_name'] = $store['store_name'];
        }

        $store = Store::getBaseList();
        if (!empty($where['start'])) {
            $list->appends(['start' => $where['start']])->render();
        }
        if (!empty($where['end'])) {
            $list->appends(['end' => $where['end']])->render();
        }
        if ($storeId) {
            $list->appends(['store_id' => $storeId])->render();
        }

        return view('admin/financial/agentFinancialList',['data' => $list,'store' => $store,'statistic' => $statistic]);
    }

    /**
     * 商品统计
     */
    public function goodsStatistic()
    {
        $where['type']      = $this->requestArr['type'];
        $where['start']     = $this->requestArr['start'];
        $where['end']       = $this->requestArr['end'];
        $where['goods_ids'] = $this->requestArr['goods_id_select'];
        $limit = $this->requestArr['export_excel'] == 1 ? 100000 : 15;

        $list = GoodsRepertoryLog::getList($where, $limit);
        if ($this->requestArr['export_excel'] == 1) {
            $title    = '财务报表-商品统计';
            $titleArr = ['商品编号', '商品名称', '变动类型', '变动对象', '零售价格/元', '变动数量', '变动日期'];
            $dataArr  = [];
            foreach ($list as $k => $item) {
                $dataArr[$k]['goods_sn']   = $item['goods_sn'];
                $dataArr[$k]['goods_name'] = $item['goods_name'];
                $dataArr[$k]['type']       = $item['type'] == 1 ? '出库' : '入库';
                $dataArr[$k]['store_name'] = $item['store_name'];
                $dataArr[$k]['old_price']  = $item['old_price'];
                $dataArr[$k]['goods_num']  = $item['goods_num'];
                $dataArr[$k]['created_at'] = $item['created_at'];
            }
            if (empty($dataArr)) {
                view()->share('layout_message', '暂无导出数据');
            } else {
                Texcel::exportExcelHtml($title, $titleArr, $dataArr);
            }
            exit();
        }

        if (!empty($where['start'])) {
            $list->appends(['start' => $where['start']])->render();
        }
        if (!empty($where['end'])) {
            $list->appends(['end' => $where['end']])->render();
        }
        if (!empty($where['type'])) {
            $list->appends(['type' => $where['type']])->render();
        }
        if (!empty($where['goods_ids'])) {
            $list->appends(['goods_id_select' => $where['goods_ids']])->render();
        }

        return view('admin/financial/goodsStatistic',['data' => $list]);
    }

    /**
     * 库存报表
     */
    public function inventoryReport()
    {
        $type  = $this->requestArr['type'] ?? 1;
        $start = $this->requestArr['start'];
        $end   = $this->requestArr['end'];
        $goodsName = $this->requestArr['goods_name'];
        $limit = $this->requestArr['export_excel'] == 1 ? 100000 : 15;
        $goods = Goods::getList(['goods_name' => $goodsName], $limit);

        if (empty($start) && empty($end)) {
            if ($type == 1) {       // 日报
                $start = date('Y-m-d').' 00:00:00';
                $end   = date('Y-m-d H:i:s',time());
            } elseif ($type == 2) { // 月报
                $startstamp = mktime(0, 0, 0, date('m'), 1, date('Y'));
                $start      = date('Y-m-d H:i:s', $startstamp);
                $endstamp   = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
                $end        = date('Y-m-d H:i:s', $endstamp);
            } elseif ($type == 3) { // 年报
                $startstamp = mktime(0, 0, 0, 1, 1, date('Y'));
                $start      = date('Y-m-d H:i:s', $startstamp);
                $endstamp   = mktime(23, 59, 59, 12, 31, date('Y'));
                $end        = date('Y-m-d H:i:s', $endstamp);
            }
        }

        $where['start'] = $start;
        $where['end']   = $end;
        foreach ($goods as &$good) {
            $good['qckc'] = 0;
            $good['rk']   = 0;
            $good['xs']   = 0;
            $good['xse']  = 0;
            $good['kc']   = 0;
            $where['goods_id'] = $good['id'];
            $all = GoodsRepertoryLog::getAll($where);
            if (count($all)) {
                $first = $all[0];
                $end   = end($all);
                if ($first['type'] == 1) {          // 出库
                    $good['qckc'] = $first['goods_after_num'] + $first['goods_num'];
                } elseif ($first['type'] == 2) {    // 入库
                    $good['qckc'] = $first['goods_after_num'] - $first['goods_num'];
                }
                $good['kc']   = $end['goods_after_num'];
                foreach ($all as $a) {
                    if ($a['type'] == 1) {  // 出库
                        $good['xs']+=$a['goods_num'];
                        $good['xse']+=$a['goods_money'];
                    }
                    if ($a['type'] == 2) {  // 入库
                        $good['rk']+=$a['goods_num'];
                    }
                }
            } else {
                // 获取最后一条记录
                $last = GoodsRepertoryLog::getLast(['goods_id' => $good['id']]);
                if ($last) {
                    $last = $last->toArray();
                    $good['qckc'] = $last['goods_after_num'];
                    $good['kc']   = $last['goods_after_num'];
                }
            }
        }
        if ($this->requestArr['export_excel'] == 1) {
            $title    = '财务报表-库存报表';
            $titleArr = ['商品编号', '商品名称', '零售价格/元', '期初库存/瓶', '入库/瓶', '销售/瓶', '销售额/元', '库存/瓶'];
            $dataArr  = [];
            foreach ($goods as $k => $item) {
                $dataArr[$k]['goods_sn']    = $item['goods_sn'];
                $dataArr[$k]['goods_name']  = $item['goods_name'];
                $dataArr[$k]['goods_price'] = $item['goods_price'];
                $dataArr[$k]['qckc']        = $item['qckc'];
                $dataArr[$k]['rk']          = $item['rk'];
                $dataArr[$k]['xs']          = $item['xs'];
                $dataArr[$k]['xse']         = $item['xse'];
                $dataArr[$k]['kc']          = $item['kc'];
            }
            if (empty($dataArr)) {
                view()->share('layout_message', '暂无导出数据');
            } else {
                Texcel::exportExcelHtml($title, $titleArr, $dataArr);
            }
            exit();
        }

        if (!empty($this->requestArr['type'])) {
            $goods->appends(['type' => $this->requestArr['type']])->render();
        }
        if (!empty($this->requestArr['start'])) {
            $goods->appends(['start' => $this->requestArr['start']])->render();
        }
        if (!empty($this->requestArr['end'])) {
            $goods->appends(['end' => $this->requestArr['end']])->render();
        }
        if (!empty($goodsName)) {
            $goods->appends(['goods_name' => $goodsName])->render();
        }

        return view('admin/financial/inventoryReport',['data' => $goods]);
    }

    /**
     * 商品台账
     */
    public function commodityParameter()
    {
        $where['start']     = $this->requestArr['start'];
        $where['end']       = $this->requestArr['end'];
        $where['goods_ids'] = $this->requestArr['goods_id_select'];
        $limit = $this->requestArr['export_excel'] == 1 ? 100000 : 15;

        $list = StockOrderGoods::getListByWhere($where, $limit);
        foreach ($list as $val) {
            $val['date']  = date('Y-m-d',strtotime($val['created_at']));
            $val['year']  = date('Y',strtotime($val['created_at']));
            $val['month'] = date('m',strtotime($val['created_at']));
            $val['day']   = date('d',strtotime($val['created_at']));
        }

        if ($this->requestArr['export_excel'] == 1) {
            $title    = '财务报表-商品台账';
            $titleArr = ['日期', '年', '月', '日', '单号', '类型', '购货单位', '商品编号', '商品名称', '商品规格', '商品单位', '商品价格', '数量'];
            $dataArr  = [];
            foreach ($list as $k => $item) {
                $dataArr[$k]['date']                = $item['date'];
                $dataArr[$k]['year']                = $item['year'];
                $dataArr[$k]['month']               = $item['month'];
                $dataArr[$k]['day']                 = $item['day'];
                $dataArr[$k]['order_sn']            = $item['order_sn'];
                $dataArr[$k]['type']                = $item['type'] == 1 ? '出库' : '入库';
                $dataArr[$k]['store_name']          = $item['type'] == 2 ? 'ENC' : $item['store_name'];
                $dataArr[$k]['goods_sn']            = $item['goods_sn'];
                $dataArr[$k]['goods_name']          = $item['goods_name'];
                $dataArr[$k]['goods_specification'] = $item['goods_specification'];
                $dataArr[$k]['goods_unit']          = $item['goods_unit'];
                $dataArr[$k]['goods_price']         = $item['is_give'] == 1 ? $item['goods_price'].'（赠送）' : $item['goods_price'];
                $dataArr[$k]['goods_number']        = $item['goods_number'];
            }
            if (empty($dataArr)) {
                view()->share('layout_message', '暂无导出数据');
            } else {
                Texcel::exportExcelHtml($title, $titleArr, $dataArr);
            }
            exit();
        }

        if (!empty($where['start'])) {
            $list->appends(['start' => $where['start']])->render();
        }
        if (!empty($where['end'])) {
            $list->appends(['end' => $where['end']])->render();
        }
        if (!empty($where['goods_ids'])) {
            $list->appends(['goods_id_select' => $where['goods_ids']])->render();
        }

        return view('admin/financial/commodityParameter',['data' => $list]);
    }

    /**
     * 商品月报
     */
    public function goodsMonthlyReport()
    {
        $month = $this->requestArr['month'];
        if (empty($month)) {     # 默认当前月份
            $startStamp = mktime(0, 0, 0, date('m'), 1, date('Y'));
            $start = date('Y-m-d H:i:s', $startStamp);
            $endStamp = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
            $end = date('Y-m-d H:i:s', $endStamp);
            $month = date('Y-m');
        } else {
            $startStamp = mktime(0, 0, 0, date('m',strtotime($month)), 1, date('Y',strtotime($month)));
            $start = date('Y-m-d H:i:s', $startStamp);
            $endStamp = mktime(23, 59, 59, date('m',strtotime($month)), date('t',strtotime($month)), date('Y',strtotime($month)));
            $end = date('Y-m-d H:i:s', $endStamp);
        }

        $startDay = date('d',strtotime($start));
        $endDay   = date('d',strtotime($end));
        $length   = $endDay - $startDay;
        for ($i=0; $i<=$length; $i++) {
            $date[$i]['start'] = date('Y-m-d 0:0:0' ,strtotime( '+' . ($i-$length) .' days', strtotime($end)));;
            $date[$i]['end']   = date('Y-m-d 23:59:59' ,strtotime( '+' . ($i-$length) .' days', strtotime($end)));
            $day[]             = (int)date('d' ,strtotime( '+' . ($i-$length) .' days', strtotime($end)));
        }

        $goods = Goods::getAll();
        $goodsIds =array_column($goods,'id');
        $where[] = ['so.type', '=', 1];
        $where[] = ['sog.created_at', '>=', strtotime($start)];
        $where[] = ['sog.created_at', '<=', strtotime($end)];
        // $list = StockOrderGoods::where($where)->whereIn('goods_id',$goodsIds)->select('id','goods_id','goods_number','created_at')->get()->toArray();

        $list = StockOrderGoods::from('stock_order_goods as sog')
                ->leftJoin('stock_order as so', 'so.id', '=', 'sog.order_id')
                ->where($where)
                ->whereIn('sog.goods_id',$goodsIds)
                ->select('sog.id','sog.goods_id','sog.goods_number','sog.created_at')
                ->get()
                ->toArray();

        foreach ($goods as &$good) {
            unset($good['goods_price']);
            unset($good['goods_sale_num']);
            for ($i=0; $i<=$length; $i++) {
                $good[$i+1] = '';
                foreach ($list as $val) {
                    if ($val['goods_id'] == $good['id']) {
                        if (strtotime($val['created_at']) >= strtotime($date[$i]['start']) && strtotime($val['created_at']) <= strtotime($date[$i]['end'])) {
                            if ($val['goods_number']) {
                                $good[$i+1] = (int)$good[$i+1] + $val['goods_number'];
                            }
                        }
                    }
                }
            }
        }

        # 整合数据
        $dataArr  = [];
        foreach ($goods as $k => $item) {
            $dataArr[$k]['goods_sn']   = $item['goods_sn'];
            $dataArr[$k]['goods_name'] = $item['goods_name'];
            $total = 0;
            for ($i=0; $i<=$length; $i++) {
                $dataArr[$k][$i+1] = $item[$i+1];
                if ($item[$i+1]) {
                    $total = $total + (int)$item[$i+1];
                }
            }
            $dataArr[$k]['total'] = $total;
        }
        $statistic = Array();
        for ($i=0; $i<=$length; $i++) {
            $statistic[$i+1] = 0;
        }
        foreach ($dataArr as $ckey=>$cval) {
            foreach ($cval as $ck=>$cv) {
                if ($ck == 'goods_sn' || $ck == 'goods_name' || $ck == 'total') {
                    continue;
                } else {
                    $statistic[$ck] = (int)$cv + $statistic[$ck];
                }
            }
        }

        $tmp = Array();
        foreach ($dataArr as $dkk=>$dvv) {
            if (strstr($dvv['goods_sn'], 'TEST') === false) {
                unset($dataArr[$dkk]);
                $tmp[] = $dvv;
            }
        }
        $dataArr = array_merge($tmp,$dataArr);

        $len = count($dataArr);
        $dataArr[$len]['goods_sn']   = '小计';
        $dataArr[$len]['goods_name'] = '';
        $dataArr[$len] = array_merge($dataArr[$len],$statistic);
        $dataArr[$len] = array_merge($dataArr[$len],[array_sum($statistic)]);

        $titleArr = ['序号', '商品名称'];
        for ($i=0; $i<=$length; $i++) {
            $titleArr[] = $i+1;
        }
        $titleArr[] = '销售/瓶';

        if ($this->requestArr['export_excel'] == 1) {
            $title = '财务报表-商品月报（' . $month . '月）';
            if (empty($dataArr)) {
                view()->share('layout_message', '暂无导出数据');
            } else {
                Texcel::exportExcelHtml($title, $titleArr, $dataArr);
            }
            exit();
        }

        return view('admin/financial/goodsMonthlyReport',['data' => $dataArr,'title' => $titleArr,'month' => $month]);
    }

    /**
     * 代理商年报
     */
    public function agentYearReport()
    {
        $resultArr = Array();
        $storeId   = $this->requestArr['store_id'];
        $titleArr  = ['月份', '发货额', '来款额', '货款余额', '未开票金额', '管理费余额', '应收运费', '赠品额'];

        if ($storeId) {
            $store = Store::getInfoById($storeId);
            $year  = $this->requestArr['year'];
            if (empty($year)) {
                $year = date('Y');  # 默认当年
            }
            $yearArr  = Array();
            $monthArr = Array();
            for ($i=1; $i <=12 ; $i++) {
                $yearArr[$i] = $year.'-'.$i;
            }
            foreach ($yearArr as $key => $value) {
                $timeStamp = strtotime($value);
                $startTime = date('Y-m-1 00:00:00', $timeStamp);
                $mDays     = date( 't', $timeStamp );
                $end_time  = date( 'Y-m-' . $mDays . ' 23:59:59', $timeStamp );
                $monthArr[$key]['start_time'] = $startTime;
                $monthArr[$key]['end_time']   = $end_time;
                if ($key == 1) {
                    $start = $startTime;
                }
                if ($key == 12) {
                    $end = $end_time;
                }
            }

            // 获取赠品
            $stockWhere[] = ['sog.is_give','=',1];
            $stockWhere[] = ['sog.store_id','=',$storeId];
            $stockWhere[] = ['sog.created_at','>=',strtotime($start)];
            $stockWhere[] = ['sog.created_at','<=',strtotime($end)];
            $gives = StockOrderGoods::from('stock_order_goods as sog')
                ->where($stockWhere)
                ->leftJoin('goods as g', 'g.id', '=', 'sog.goods_id')
                ->select('sog.created_at','sog.goods_number','g.goods_price')
                ->get();

            // 获取资金流水 1 => '货款充值', 2 => '管理费充值', 3 => '货款出账', 4 => '管理费出账', 5 => '运费(从货款扣除)', 6 => '运费(从管理费扣除)'
            $accounts = Account::where(['account_id' => $storeId])->get();
            foreach ($accounts as $v) {
                $accountIds[] = $v['id'];
            }
            $where = ['start' => $start,'end' => $end,'account_ids' => $accountIds];
            $list  = AccountMoneyChange::getList($where,100000000);

            $dataArr  = Array();
            foreach ($monthArr as $mkey=>$mval) {
                $dataArr[$mkey]['month'] = $mkey.'月';
                $dataArr[$mkey]['fhe']   = 0;
                $dataArr[$mkey]['lke']   = 0;
                $dataArr[$mkey]['hkye']  = 0;
                $dataArr[$mkey]['wkpje'] = 0;
                $dataArr[$mkey]['glfye'] = 0;
                $dataArr[$mkey]['ysyf']  = 0;
                $dataArr[$mkey]['zpe']   = 0;
                foreach ($list as $li) {
                    if ($li->created_at >= strtotime($mval['start_time']) && $li->created_at <= strtotime($mval['end_time'])) {
                        if ($li->consume_type == 1) {
                            $dataArr[$mkey]['lke']+=$li->money;
                        }
                        if ($li->consume_type == 3) {
                            $dataArr[$mkey]['fhe']+=$li->money;
                        }
                        if ($li->consume_type == 5) {
                            $dataArr[$mkey]['ysyf']+=$li->money;
                        }
                        if ($li->consume_type == 6) {
                            $dataArr[$mkey]['ysyf']+=$li->money;
                        }
                        if ($li->consume_type == 1 || $li->consume_type == 3 || $li->consume_type == 5) {
                            if ($dataArr[$mkey]['hkye']) {
                                continue;
                            }
                            if ($li->consume_type == 1) {
                                $dataArr[$mkey]['hkye'] = $li->to_money_after;
                            }
                            if ($li->consume_type == 3 || $li->consume_type == 5) {
                                $dataArr[$mkey]['hkye'] = $li->money_after;
                            }
                        }
                        if ($li->consume_type == 2 || $li->consume_type == 4 || $li->consume_type == 6) {
                            if ($dataArr[$mkey]['glfye']) {
                                continue;
                            }
                            if ($li->consume_type == 2) {
                                $dataArr[$mkey]['glfye'] = $li->to_money_after;
                            }
                            if ($li->consume_type == 4 || $li->consume_type == 6) {
                                $dataArr[$mkey]['glfye'] = $li->money_after;
                            }
                        }
                    }
                }
                foreach ($gives as $g) {
                    if (strtotime($g->created_at) >= strtotime($mval['start_time']) && strtotime($g->created_at) <= strtotime($mval['end_time'])) {
                        $zpe = $g->goods_price * $g->goods_number;
                        $dataArr[$mkey]['zpe']+=$zpe;
                    }
                }
            }

            $quarterOne = ['month' => '一季度', 'fhe' => 0, 'lke' => 0, 'hkye' => 0, 'wkpje' => 0, 'glfye' => 0, 'ysyf' => 0, 'zpe' => 0];
            $quarterTwo = ['month' => '二季度', 'fhe' => 0, 'lke' => 0, 'hkye' => 0, 'wkpje' => 0, 'glfye' => 0, 'ysyf' => 0, 'zpe' => 0];
            $quarterThr = ['month' => '三季度', 'fhe' => 0, 'lke' => 0, 'hkye' => 0, 'wkpje' => 0, 'glfye' => 0, 'ysyf' => 0, 'zpe' => 0];
            $quarterFor = ['month' => '四季度', 'fhe' => 0, 'lke' => 0, 'hkye' => 0, 'wkpje' => 0, 'glfye' => 0, 'ysyf' => 0, 'zpe' => 0];
            $yearFirst  = ['month' => '上半年度', 'fhe' => 0, 'lke' => 0, 'hkye' => 0, 'wkpje' => 0, 'glfye' => 0, 'ysyf' => 0, 'zpe' => 0];
            $yearLast   = ['month' => '下半年度', 'fhe' => 0, 'lke' => 0, 'hkye' => 0, 'wkpje' => 0, 'glfye' => 0, 'ysyf' => 0, 'zpe' => 0];
            $yearOne    = ['month' => '全年合计', 'fhe' => 0, 'lke' => 0, 'hkye' => 0, 'wkpje' => 0, 'glfye' => 0, 'ysyf' => 0, 'zpe' => 0];
            foreach ($dataArr as $dkey=>$dval) {
                if ($dkey == 1 || $dkey == 2 || $dkey == 3) {
                    $quarterOne['fhe']+=$dval['fhe'];
                    $quarterOne['lke']+=$dval['lke'];
                    $quarterOne['hkye']=$dval['hkye'];
                    $quarterOne['glfye']=$dval['glfye'];
                    $quarterOne['ysyf']+=$dval['ysyf'];
                    $quarterOne['zpe']+=$dval['zpe'];

                    $yearFirst['fhe']+=$dval['fhe'];
                    $yearFirst['lke']+=$dval['lke'];
                    $yearFirst['hkye']=$dval['hkye'];
                    $yearFirst['glfye']=$dval['glfye'];
                    $yearFirst['ysyf']+=$dval['ysyf'];
                    $yearFirst['zpe']+=$dval['zpe'];
                }
                if ($dkey == 4 || $dkey == 5 || $dkey == 6) {
                    $quarterTwo['fhe']+=$dval['fhe'];
                    $quarterTwo['lke']+=$dval['lke'];
                    $quarterTwo['hkye']=$dval['hkye'];
                    $quarterTwo['glfye']=$dval['glfye'];
                    $quarterTwo['ysyf']+=$dval['ysyf'];
                    $quarterTwo['zpe']+=$dval['zpe'];

                    $yearFirst['fhe']+=$dval['fhe'];
                    $yearFirst['lke']+=$dval['lke'];
                    $yearFirst['hkye']=$dval['hkye'];
                    $yearFirst['glfye']=$dval['glfye'];
                    $yearFirst['ysyf']+=$dval['ysyf'];
                    $yearFirst['zpe']+=$dval['zpe'];
                }
                if ($dkey == 7 || $dkey == 8 || $dkey == 9) {
                    $quarterThr['fhe']+=$dval['fhe'];
                    $quarterThr['lke']+=$dval['lke'];
                    $quarterThr['hkye']=$dval['hkye'];
                    $quarterThr['glfye']=$dval['glfye'];
                    $quarterThr['ysyf']+=$dval['ysyf'];
                    $quarterThr['zpe']+=$dval['zpe'];

                    $yearLast['fhe']+=$dval['fhe'];
                    $yearLast['lke']+=$dval['lke'];
                    $yearLast['hkye']=$dval['hkye'];
                    $yearLast['glfye']=$dval['glfye'];
                    $yearLast['ysyf']+=$dval['ysyf'];
                    $yearLast['zpe']+=$dval['zpe'];
                }
                if ($dkey == 10 || $dkey == 11 || $dkey == 12) {
                    $quarterFor['fhe']+=$dval['fhe'];
                    $quarterFor['lke']+=$dval['lke'];
                    $quarterFor['hkye']=$dval['hkye'];
                    $quarterFor['glfye']=$dval['glfye'];
                    $quarterFor['ysyf']+=$dval['ysyf'];
                    $quarterFor['zpe']+=$dval['zpe'];

                    $yearLast['fhe']+=$dval['fhe'];
                    $yearLast['lke']+=$dval['lke'];
                    $yearLast['hkye']=$dval['hkye'];
                    $yearLast['glfye']=$dval['glfye'];
                    $yearLast['ysyf']+=$dval['ysyf'];
                    $yearLast['zpe']+=$dval['zpe'];
                }

                $yearOne['fhe']+=$dval['fhe'];
                $yearOne['lke']+=$dval['lke'];
                $yearOne['hkye']=$dval['hkye'];
                $yearOne['glfye']=$dval['glfye'];
                $yearOne['ysyf']+=$dval['ysyf'];
                $yearOne['zpe']+=$dval['zpe'];
            }

            foreach ($dataArr as $dk=>$dv) {
                if ($dk == 1 || $dk == 2 || $dk == 4 || $dk == 5 || $dk == 7 || $dk == 8 || $dk == 10 || $dk == 11) {
                    $resultArr[] = $dv;
                }
                if ($dk == 3) {
                    $resultArr[] = $dv;
                    $resultArr[] = $quarterOne;
                }
                if ($dk == 6) {
                    $resultArr[] = $dv;
                    $resultArr[] = $quarterTwo;
                    $resultArr[] = $yearFirst;
                }
                if ($dk == 9) {
                    $resultArr[] = $dv;
                    $resultArr[] = $quarterThr;
                }
                if ($dk == 12) {
                    $resultArr[] = $dv;
                    $resultArr[] = $quarterFor;
                    $resultArr[] = $yearLast;
                    $resultArr[] = $yearOne;
                }
            }

            if ($this->requestArr['export_excel'] == 1) {
                $title = $store['store_name'] . '年报（' . $year . '）';
                if (empty($dataArr)) {
                    view()->share('layout_message', '暂无导出数据');
                } else {
                    Texcel::exportExcelHtml($title, $titleArr, $resultArr);
                }
                exit();
            }
        }

        $stores = Store::getBaseList();

        return view('admin/financial/agentYearReport',['stores' => $stores,'data' => $resultArr,'title' => $titleArr,'store' => $store]);
    }
}
